<!-- eslint-disable vue/no-lone-template -->
<template>
	<div class="app-container">
		<el-row class="yd-form-wraper" justify="space-between">
			<el-col :span="6">
				<el-button type="primary" @click="toAddTask">添加任务</el-button>
				<el-button plain :disabled="ids.length === 0" @click="deleteMany">删除任务</el-button>
			</el-col>
			<el-col :span="6">
				<el-form :inline="true" :model="searchFormData" style="display: flex">
					<el-form-item style="width: 500px; margin-right: 15px">
						<el-input v-model="searchFormData.taskName" placeholder="请输入任务名称" clearable />
					</el-form-item>
					<el-form-item style="margin-right: 0">
						<el-button plain @click="searchHandler">查询</el-button>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<YdTable
			:formData="searchFormData"
			:tableConfig="tableConfig"
			:tableData="tableData"
			@sizeChangeHandler="searchHandler"
			@currentChangeHandler="queryGrid"
			@sortChangeHandler="queryGrid"
			@selectionChangeHandler="handleSelectionChange"
		></YdTable>
	</div>
</template>
<script lang="tsx" name="taskManagement" setup>
import { ref, reactive, toRefs, onMounted, onActivated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { right } from '@antv/x6/lib/registry/port-layout/line';
import { getTaskInfoList, saveTaskInfo, deleteTaskByIds, stopTaskByIds, startTaskByIds } from '@/api/ops-workbench/timeSchedule/taskManagement';
const { proxy } = useCurrentInstance();
const router = useRouter();
const route = useRoute();
const emit = defineEmits(['changeComponent']);
let ids = ref([]);
// 任务名称
// let taskName = ref('');
let searchFormData = reactive<anyObj>({
	taskName: '',
});
let tableData = ref<anyObj>([]);
const tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '任务名称',
			prop: 'taskName',
		},
		{
			label: '使用模板',
			prop: 'reportTemplateName',
		},
		{
			label: '上次运行时间',
			prop: 'taskPreviousTime',
			sortable: true,
		},
		{
			label: '接下来的运行时间',
			prop: 'taskNextTime',
			sortable: true,
		},
		{
			label: '运行状态',
			prop: 'taskState',
			formatter(row: any, val: any) {
				console.log(row, val);
				if (val === 0) {
					return '已暂停';
				} else if (val === 1) {
					return '运行中';
				} else return '已结束';
			},
			width: 120,
		},
		{
			label: '任务执行状态',
			prop: 'taskExecuteStatus',
			formatter(row: any, val: any) {
				console.log(row, val);
				if (val === 0) {
					return '异常/失败';
				} else if (val === 1) {
					return '正常';
				}
			},
			width: 120,
		},
		{
			label: '操作',
			prop: '',
			width: 300,
			operation: [
				{
					text: '执行',
					isShow: (scope: anyObj) => isAction(scope.row),
					handler: (scope: anyObj) => handleAction(scope.row),
					permi: ['taskManagement:execute'],
				},
				{
					text: '暂停执行',
					isShow: (scope: anyObj) => !isAction(scope.row),
					handler: (scope: anyObj) => stopAction(scope.row),
					permi: ['taskManagement:stopExecute'],
				},
				{
					text: '编辑',
					handler: (scope: anyObj) => handleEdit(scope.row),
					permi: ['taskManagement:Edit'],
				},
				{
					text: '复制',
					handler: (scope: anyObj) => handleCopy(scope.row),
					permi: ['taskManagement:copy'],
				},
				{
					text: '删除',
					handler: (scope: anyObj) => handleDelete(scope.row),
					permi: ['taskManagement:delete'],
				},
			],
		},
	],
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 关闭序号列
	disableOrderNumber: true,
	// 开启复选框
	enableSelection: true,
	// loading: true,
});
searchHandler();

onActivated(() => {
	searchHandler();
});

function toAddTask() {
	emit('changeComponent', 4, { taskId: 0 });
}
function searchHandler() {
	tableConfig.pagination!.pageNum = 1;
	queryGrid();
}

// 查询列表
function queryGrid() {
	tableConfig.loading = true;
	getTaskInfoList(searchFormData).then((res: ApiResponse) => {
		tableConfig.loading = false;
		if (res.code !== 0) {
			proxy?.$message.error(res.msg);
			return;
		}
		tableData.value = res.data.records;
		tableConfig.pagination!.total = res.data.total;
	});
}

/**多选框选中数据*/
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: anyObj) => item.id);
}
// 执行
function handleAction(row: anyObj) {
	if (row.taskExecuteStatus === 0) {
		proxy.$modal.msgWarning('任务为异常状态，无法进行执行操作');
	} else {
		startTaskByIds(row.id).then((res) => {
			if (res.code === 0) {
				proxy.$modal.msgSuccess(res.data);
				queryGrid();
			} else {
				proxy.$modal.msgError(res.msg);
			}
		});
	}
}

function isAction(row: anyObj): boolean {
	if (row.taskState === 1) return false;
	else return true;
}
// 暂停执行
function stopAction(row: anyObj) {
	stopTaskByIds(row.id).then((res) => {
		if (res.code === 0) {
			proxy.$modal.msgSuccess(res.data);
			queryGrid();
		} else {
			proxy.$modal.msgError(res.msg);
		}
	});
}

// 编辑
function handleEdit(row: anyObj) {
	if (row.taskState === 1) proxy.$modal.msgWarning('该任务正在运行中，不可进行编辑');
	else emit('changeComponent', 4, { taskId: row.id });
}

// 复制
function handleCopy(row: anyObj) {
	tableConfig.loading = true;
	let data = JSON.parse(JSON.stringify(row));
	data.taskName = row.taskName + '-副本';
	data.id = null;
	saveTaskInfo(data)
		.then((res: ApiResponse) => {
			tableConfig.loading = false;
			if (res.code === 0) {
				queryGrid();
			} else {
				proxy.$modal.msgError(res.msg);
			}
		})
		.catch((e) => {
			proxy.$modal.msgError(e);
		});
}
// 删除一行
function handleDelete(row: anyObj) {
	tableConfig.loading = true;
	deleteTaskByIds(row.id).then((res: ApiResponse) => {
		tableConfig.loading = false;
		if (res.code === 0) {
			queryGrid();
			proxy.$modal.msgSuccess('删除成功');
		} else {
			proxy.$modal.msgError(res.msg);
		}
	});
}
// 批量删除
function deleteMany(row: anyObj) {
	tableConfig.loading = true;
	let param = ids.value.toString();
	deleteTaskByIds(param).then((res: ApiResponse) => {
		tableConfig.loading = false;
		if (res.code === 0) {
			queryGrid();
			proxy.$modal.msgSuccess('删除成功');
		} else {
			proxy.$modal.msgError(res.msg);
		}
	});
}
</script>
<style lang="scss" scoped>
body[data-theme='theme-dark'] {
	.el-input {
		width: 100%;
	}
}
</style>
